package com.example.sbeducation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sbeducation.dto.LoginDTO;
import com.example.sbeducation.dto.PasswordChangeDTO;
import com.example.sbeducation.dto.UserInfoDTO;
import com.example.sbeducation.entity.User;
import com.example.sbeducation.exception.BusinessException;
import com.example.sbeducation.mapper.UserMapper;
import com.example.sbeducation.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

  private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

  @Override
  public UserInfoDTO studentLogin(LoginDTO loginDTO) {
    return login(loginDTO, "student");
  }

  @Override
  public UserInfoDTO teacherLogin(LoginDTO loginDTO) {
    return login(loginDTO, "teacher");
  }

  private UserInfoDTO login(LoginDTO loginDTO, String role) {
    // 查询用户
    User user = getUserByUsername(loginDTO.getUsername());

    // 判断用户是否存在
    if (user == null) {
      throw new BusinessException(400, "用户不存在");
    }

    // 判断角色是否正确
    if (!user.getRole().equals(role)) {
      throw new BusinessException(400, "用户角色不匹配");
    }

    // 简单密码比对，不使用加密
    if (!loginDTO.getPassword().equals(user.getPassword())) {
      throw new BusinessException(400, "密码错误");
    }

    // 封装用户信息
    UserInfoDTO userInfoDTO = new UserInfoDTO();
    BeanUtils.copyProperties(user, userInfoDTO);

    return userInfoDTO;
  }

  @Override
  public User getUserById(Long userId) {
    User user = getById(userId);
    if (user == null) {
      throw new BusinessException(400, "用户不存在");
    }
    return user;
  }

  @Override
  public User getUserByUsername(String username) {
    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(User::getUsername, username);
    return getOne(queryWrapper);
  }

  @Override
  @Transactional
  public void updateUserInfo(UserInfoDTO userInfoDTO) {
    log.info("更新用户信息开始: userId={}", userInfoDTO.getId());

    // 获取当前用户
    User user = getUserById(userInfoDTO.getId());
    log.info("当前用户信息: {}", user);

    // 只允许更新部分字段
    user.setRealName(userInfoDTO.getRealName());
    user.setEmail(userInfoDTO.getEmail());
    user.setPhone(userInfoDTO.getPhone());

    // 更新头像
    if (userInfoDTO.getAvatar() != null && !userInfoDTO.getAvatar().isEmpty()) {
      log.info("更新用户头像: 旧={}, 新={}", user.getAvatar(), userInfoDTO.getAvatar());
      user.setAvatar(userInfoDTO.getAvatar());
    }

    // 更新用户信息
    boolean success = updateById(user);
    log.info("用户信息更新结果: {}", success ? "成功" : "失败");
  }

  @Override
  @Transactional
  public void changePassword(PasswordChangeDTO passwordChangeDTO) {
    // 获取当前用户
    User user = getUserById(passwordChangeDTO.getUserId());

    // 验证旧密码
    if (!user.getPassword().equals(passwordChangeDTO.getOldPassword())) {
      throw new BusinessException(400, "旧密码不正确");
    }

    // 更新密码
    user.setPassword(passwordChangeDTO.getNewPassword());
    updateById(user);
  }

  @Override
  public List<UserInfoDTO> getContactsByUserRole(Long userId) {
    // 获取当前用户
    User currentUser = getUserById(userId);

    // 根据用户角色获取联系人
    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

    if ("student".equals(currentUser.getRole())) {
      // 学生获取所有教师
      queryWrapper.eq(User::getRole, "teacher");
    } else if ("teacher".equals(currentUser.getRole())) {
      // 教师获取所有学生
      queryWrapper.eq(User::getRole, "student");
    } else {
      throw new BusinessException(400, "无效的用户角色");
    }

    // 查询联系人列表
    List<User> contactUsers = list(queryWrapper);

    // 转换为DTO
    return contactUsers.stream().map(user -> {
      UserInfoDTO dto = new UserInfoDTO();
      BeanUtils.copyProperties(user, dto);
      return dto;
    }).collect(Collectors.toList());
  }
}